package leetcode.lt100;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Interval {
	int start;
	int end;

	Interval() {
		start = 0;
		end = 0;
	}

	Interval(int s, int e) {
		start = s;
		end = e;
	}
}

class Solution_55 {

	public static void main(String[] args) {
		List<Interval> intervals = new ArrayList<>();
		intervals.add(new Interval(1, 3));
		intervals.add(new Interval(2, 6));
		intervals.add(new Interval(8, 10));
		intervals.add(new Interval(15, 18));
		new Solution_55().merge(intervals);
	}

	public List<Interval> merge(List<Interval> intervals) {
		if (intervals.size() == 0)
			return intervals;
		// 排序
		Collections.sort(intervals, new Comparator<Interval>() {
			public int compare(Interval a, Interval b) {
				return a.start - b.start;
			}
		});

		List<Integer> list = new ArrayList<Integer>();
		Interval x;

		for (int i = 0; i < intervals.size();) {
			x = intervals.get(i);
			int j = i + 1;
			while (j < intervals.size() && x.end >= intervals.get(j).start) {
				x.end = Math.max(x.end, intervals.get(j).end);
				list.add(j);
				j++;
			}
			i = j;
		}

		int l = list.size();
		for (int i = 0; i < l; i++) {
			intervals.remove(list.get(i) - i);
		}

		return intervals;
	}

}